##    This file is part of The Most Awesome Story Ever
##
##    Foobar is free software: you can redistribute it and/or modify
##    it under the terms of the GNU General Public License as published by
##    the Free Software Foundation, either version 3 of the License, or
##    (at your option) any later version.
##
##    Foobar is distributed in the hope that it will be useful,
##    but WITHOUT ANY WARRANTY; without even the implied warranty of
##    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##    GNU General Public License for more details.
##
##    You should have received a copy of the GNU General Public License
##    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
##    
##    Copyright 2008, Ryan Michela

import os
import cgi
from pagemodel import Page
from google.appengine.ext import db
import fckeditor


from google.appengine.ext.webapp import template

def renderPage(response, page):
    """Render a given page from the Page database to the response output."""
    
    #render the result from the querry
    template_values = {
        'pageNum' : page.pageNum,
        'title' : cgi.escape(page.title),
        'body' : page.body,
        'imageExists' : isinstance(page.image, db.Blob),
        'imageExtension' : page.imageExtension,
        'options' : page.getOptions(),
        'newOption': (len(page.getOptions()) < 10),
    }
    
    path = os.path.join(os.path.dirname(__file__), 'templates/page.html')
    response.out.write(template.render(path, template_values))

def renderForm(response, pageNum, error='', title='', body='<p>&nbsp;</p>'):
    """Render a given form from the Page database to the response output."""
    #render the form
    template_values = {
        'title' : title,
        'error' : error,
        'pageNum' : pageNum,
        'fckeditor': getFckEditor(body)
    }
    
    path = os.path.join(os.path.dirname(__file__), 'templates/form.html')
    response.out.write(template.render(path, template_values))
    
def getFckEditor(body):
    """Create a FckEditor and return its markup as a string."""
    #load the fckeditor
    try:
        oFCKeditor = fckeditor.FCKeditor('body')
        oFCKeditor.ToolbarSet = 'Safe'
        oFCKeditor.Width = '100%'
        oFCKeditor.Height = '250'
        oFCKeditor.Value = body
        return oFCKeditor.Create()
    except Exception, e:
        return e
        

